"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('../core/mongoservice'),
    Q = require('q');

function RouteService() {
    console.log("RouteService constructor");
}
RouteService.prototype = Object.create(TokenService.prototype);
RouteService.prototype.constructor = RouteService;

RouteService.prototype.connect = function (request, response, promise) {
    return promise.then(function (self) {
        return require("../userservice").mongoGetByLoginAndPassword(request.body.login, request.body.password).then(function (user) {
            var payload = { user: { id: user._id.toString() } }
            var token = self.encode(payload);
            return response.send({ request: request, content: {route: "/", token: token} });
        });
    })
};

RouteService.prototype.connectFromToken = function (request, response, promise) {
    return promise.then(function (self) {

        self.identify(request, response);
        var userId = request.payload.user.id;

        return require("../userservice").mongoGetById(userId).then(function (user) {
            var payload = { user: { id: user._id.toString()} }
            var token = self.encode(payload);
            return response.send({ request: request, content: { route: "/", token: token} });
        });
    })
};

RouteService.prototype.index = function (request, response, promise) {
    return promise.then(function (self) {
        request.url = "/app/main.html";
        return router.assets.invoke(request, response);
    });
};

exports = module.exports = new RouteService();